package com.blog.cmrpersonalblog.factory;

import com.blog.cmrpersonalblog.enums.FileUploadType;
import com.blog.cmrpersonalblog.strategy.upload.FileUploadStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传策略工厂
 * 使用工厂模式管理不同类型的文件上传策略
 */
@Slf4j
@Component
public class FileUploadStrategyFactory {
    
    private final Map<FileUploadType, FileUploadStrategy> strategyMap = new HashMap<>();
    
    /**
     * 构造函数，自动注入所有的文件上传策略
     */
    public FileUploadStrategyFactory(List<FileUploadStrategy> strategies) {
        for (FileUploadStrategy strategy : strategies) {
            strategyMap.put(strategy.getSupportedType(), strategy);
            log.info("注册文件上传策略: {} -> {}", 
                strategy.getSupportedType().getDescription(), 
                strategy.getClass().getSimpleName());
        }
        
        log.info("文件上传策略工厂初始化完成，共注册 {} 个策略", strategyMap.size());
    }
    
    /**
     * 根据上传类型获取对应的策略
     * 
     * @param uploadType 上传类型
     * @return 对应的上传策略
     * @throws IllegalArgumentException 如果没有找到对应的策略
     */
    public FileUploadStrategy getStrategy(FileUploadType uploadType) {
        FileUploadStrategy strategy = strategyMap.get(uploadType);
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的文件上传类型: " + uploadType.getDescription());
        }
        return strategy;
    }
    
    /**
     * 根据类型代码获取对应的策略
     * 
     * @param typeCode 类型代码
     * @return 对应的上传策略
     */
    public FileUploadStrategy getStrategy(String typeCode) {
        FileUploadType uploadType = FileUploadType.fromCode(typeCode);
        return getStrategy(uploadType);
    }
    
    /**
     * 检查是否支持指定的上传类型
     * 
     * @param uploadType 上传类型
     * @return 是否支持
     */
    public boolean isSupported(FileUploadType uploadType) {
        return strategyMap.containsKey(uploadType);
    }
    
    /**
     * 检查是否支持指定的类型代码
     * 
     * @param typeCode 类型代码
     * @return 是否支持
     */
    public boolean isSupported(String typeCode) {
        try {
            FileUploadType uploadType = FileUploadType.fromCode(typeCode);
            return isSupported(uploadType);
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
    
    /**
     * 获取所有支持的上传类型
     * 
     * @return 支持的上传类型集合
     */
    public Map<FileUploadType, FileUploadStrategy> getAllStrategies() {
        return new HashMap<>(strategyMap);
    }
}
